import struct

from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from typing import Tuple
from models import GpsData, BaseData, Audio, Video, Key
import threading
from queue import Queue
import asyncio
import time
import random
import re
import socket


class MySocketServer(threading.Thread):

    def __init__(self, address: Tuple[str, int]):
        super().__init__()
        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.__socket.bind(address)
        self.gpsDict = {
            'lit': 106.640491,
            'dim': 26.39043,
            'angle': 127
        }

    def run(self) -> None:
        package = struct.Struct("< f f f")
        while True:
            rawData, _ = self.__socket.recvfrom(1024)
            data = package.unpack(rawData)
            self.gpsDict['lit'] = data[0]
            self.gpsDict['dim'] = data[1]
            self.gpsDict['angle'] = data[2]


server = MySocketServer(('127.0.0.1', 9999))
server.setDaemon(True)
server.start()

router = APIRouter(
    prefix="/Ui",
    tags=["UI系统"]
)

pointList = [
    (106.640491, 26.39043),
    (106.640536, 26.390365),
    (106.640608, 26.390272),
    (106.640712, 26.390187),
    (106.640725, 26.390147),
    (106.640851, 26.390098),
    (106.641004, 26.390082),
    (106.641179, 26.390066),
    (106.641273, 26.390053),
    (106.641327, 26.390045),
    (106.641538, 26.389981),
    (106.641866, 26.389989)
]
nums = 0


@router.get("/GpsInfo", response_model=GpsData)
async def get_gps():
    global nums
    # 获取GPS数据的相关操作
    content = {
        'lit': server.gpsDict['lit'],
        'dim': server.gpsDict['dim'],
        'angle': server.gpsDict['angle']
    }
    headers = {
        'Access-Control-Allow-Origin': '*'
    }
    return JSONResponse(content=content, headers=headers)


@router.get("/getBase", response_model=BaseData)
async def get_base():
    # 获取电量、信号、速度的相关数据
    # return {
    #     'batValue': random.uniform(1.2, 100.0),
    #     'sigValue': random.randint(0, 5),
    #     'speedValue': random.uniform(0.0, 20.0)
    # }
    return {
        'batValue': 123.23,
        'sigValue': 123,
        'speedValue': 123.43
    }


@router.get("/setAudio")
async def set_audio(status: bool = Audio):
    # 根据status设置音频是否关闭
    return {
        'status': status
    }


@router.get("/setVideo")
async def set_video(status: bool = Video):
    # 根据status设置视频是否关闭
    return {
        'status': status
    }


@router.get("/sendKey")
async def send_Key(key: str = Key):
    # 根据发送的按键来进行操作
    pass
